/* 
 * File:   SDrivePeer.c
 * Author: alex
 *
 * Created on June 9, 2009, 11:30 AM
 */

#include <stdio.h>
#include <stdlib.h>
#include "mod_utils.h"
#include "mod_error.h"
#include "mod_config.h"
#include "mod_file.h"
#include "structures.h"
#include "mod_network.h"
#include "mod_protocol.h"
#include <glib-2.0/glib.h>
/*
 *
 */
PeerConfig *pconf;
GList * listaPeer;
GList * listaChunk;
void manageRequest(){
    
    struct sockaddr_in addr;
    int sd=0;
   // int sd = create_TCP_client_socket(pconf->spipaddress, pconf->spportlisten, &addr);
    if ((sd = create_TCP_server_socket(pconf->port, 50, &addr)) < 0) {
        return -1;
    }
    int cd=0, tr1=0;

    pthread_t thread1;

    while(1){

        cd = accept_connection(&sd, &addr);

        //a questo punto creo il thread di gestione
        if( (tr1=pthread_create( &thread1, NULL, handleOperation, cd)) )
        {
            perror("Errore creazione thread2\n");
        }
        cd = 0;
    }
}
int main(int argc, char** argv) {
  pconf = loadPeerConfig("peerconfig.conf");

  /*
  int csd=0;
  int nChunk=0;
  int nChunkNew=0;
  splitFileAndSend(&csd,"/home/alex/","tot.txt",&nChunk);
  struct chunkLight * cl = NULL;
  cl = readAllChunk(&nChunkNew);
  char *nomeFile = "tot.txt";
  rebuildFile(nomeFile, nChunkNew, cl);
  */

   // int sd = create_TCP_client_socket(pconf->spipaddress, pconf->spportlisten, &addr);
  pthread_t thread2 =0;
  int tr2=0;
  if( (tr2=pthread_create( &thread2, NULL, manageRequest, NULL)) )
        {
            perror("Errore creazione thread2\n");
        }
    /*int cd=0,tr1=0;

    pthread_t thread1;

    while(1){

        cd = accept_connection(&sd, &addr);

        //a questo punto creo il thread di gestione
        if( (tr1=pthread_create( &thread1, NULL, handleOperation, cd)) )
        {
            perror("Errore creazione thread2\n");
        }
        cd = 0;
    }*/

   

   //splitFileAndSend(4,"/home/alex/SD/toPut/", "prova2.txt");
    //int nF=0;
    //int nChunk=0;
   // printf("%d\n",countAllFile());
   // printf("%s\n",readAllFile(&nF));
//    struct chunkLight * cl = readAllChunk(&nChunk);
    //nChunk = countAllChunk();
    //printf("%d niente\n",nChunk);
   request_peer_join();
   //sleep(3);
   //char * nomefile = calloc(100,sizeof(char));
   //strcpy(nomefile,"testoProg.txt");
   //request_peer_put(nomefile);
   sleep(5);
   request_peer_leave();
   //sleep(3);
   //request_peer_join();
   //sleep(2);
   //request_peer_leave();

     return (EXIT_SUCCESS);
}

